package com.engine.zhlx.ec.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.zhlx.ec.utils.EcDataUtil;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2023-12-30
 * @Description: Sap主动推送信息
 * @ModifyLog:
 **/

public class WeaPushEcDataWeb extends BaseBean {
    /**
     * @Description: EC推送资金计划汇总信息到资金系统(拜特)
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023-09-10  https://ec.zhlxsemicon.com:88/api/weaPushEcDataWebApi/pushZjjhhzData
     */
    @POST
    @Path("/pushZjjhhzData")
    @Produces({MediaType.TEXT_PLAIN})
    public String pushZjjhhzData(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String code = "success";
        String message = "";
        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            RecordSet rs = new RecordSet();
            String curMonth = DateUtil.getCurrentDate().substring(0, 7);
            String ids = Util.null2String(request.getParameter("ids"));
            writeLog(">>>>>pushZjjhhzData>>>ids=" + ids);
            String sql = "select * from uf_zjjhhzb where nvl(czzt,1)=1 and substr(sqrq,0,7)='" + curMonth + "'";
            if (!"".equals(ids)) {
                sql += " and id in (" + ids + ")";
            }
            JSONArray dataArry = new JSONArray();
            rs.executeQuery(sql);
            while (rs.next()) {
                JSONObject dataJson = new JSONObject();
                //计划ID
                dataJson.put("DETAIL_ID", Util.null2String(rs.getString("jhid")));
                //来源
                dataJson.put("DATA_SOURCE", "EC");
                String ly = Util.null2String(rs.getString("ly"));
                if ("1".equals(ly) || "3".equals(ly) || "5".equals(ly)) {
                    dataJson.put("CD_SIGN", "0");
                }
                if ("0".equals(ly) || "2".equals(ly) || "4".equals(ly) || "6".equals(ly)) {
                    dataJson.put("CD_SIGN", "1");
                }
                //资金明细项目
                dataJson.put("DETAIL_TEXT", Util.null2String(rs.getString("zjmxxmwb")));
                //预算编码
                dataJson.put("ITEM_CODE", Util.null2String(rs.getString("ysbm")));
                //预算科目
                dataJson.put("ITEM_NAME", Util.null2String(rs.getString("ysxm")));
                //公司代码
                dataJson.put("CORP_CODE", Util.null2String(rs.getString("gsdm")));
                //公司名称
                dataJson.put("CORP_NAME", Util.null2String(rs.getString("gsmc")));
                //客商编码
                dataJson.put("CS_CODE", Util.null2String(rs.getString("ksbm")));
                //客商名称
                dataJson.put("CS_NAME", Util.null2String(rs.getString("ksmc")));
                //支付方式
                String zffs = Util.null2String(rs.getString("zffsxl"));
                String voucherType = "0".equals(zffs) ? "06" : "70";
                dataJson.put("VOUCHER_TYPE", voucherType);
                //币种
                dataJson.put("CUR", Util.null2String(rs.getString("bz")));
                //交易支付内容
                dataJson.put("ABS", Util.null2String(rs.getString("jyzfnr")));
                String ywqrr = Util.null2String(rs.getString("ywqrr"));
                //业务确认人
                dataJson.put("BUSINESS_USER", resourceComInfo.getLastname(ywqrr));
                String tbbm = Util.null2String(rs.getString("tbbm"));
                //填报部门
                dataJson.put("DEPT_NAME", departmentComInfo.getDepartmentname(tbbm));
                //填报部门编码
                dataJson.put("DEPT_CODE", departmentComInfo.getDepartmentCode(tbbm));
                //财务复核金额（原币）
                dataJson.put("AMOUNT_Y", Util.null2String(rs.getString("cwfhjeyb")));
                //财务复核金额（本币）
                dataJson.put("AMOUNT_B", Util.null2String(rs.getString("cwfhjebb")));
                //开户银行（电汇）
                dataJson.put("PAYEE_BANK1", Util.null2String(rs.getString("khyxdh")));
                //联行号（电汇）
                dataJson.put("PAYEE_BANK_CODE1", Util.null2String(rs.getString("lxhdh")));
                //银行账号（电汇）
                dataJson.put("PAYEE_ACC_NO1", Util.null2String(rs.getString("yxzhdh")));
                //开户银行（承兑）
                dataJson.put("PAYEE_BANK2", Util.null2String(rs.getString("khyxcd")));
                //联行号（承兑）
                dataJson.put("PAYEE_BANK_CODE2", Util.null2String(rs.getString("lxhcd")));
                //银行账号（承兑）
                dataJson.put("PAYEE_ACC_NO2", Util.null2String(rs.getString("yxzhcd")));
                //批量/单笔
                dataJson.put("IS_BATCH", Util.null2String(rs.getString("pldb")));
                dataArry.add(dataJson);
            }
            if (!dataArry.isEmpty()) {
                JSONObject jsonData = new JSONObject();
                jsonData.put("totalcount", dataArry.size());
                writeLog(">>>>>pushZjjhhzData>>>>>dataArry=" + dataArry);
                JSONObject resultJson = EcDataUtil.saveFundingPlan(dataArry);
                writeLog(">>>>>pushZjjhhzData>>>>>resultJson=" + resultJson);
                code = Util.null2String(resultJson.getString("code"));
                int failcount = 0;
                int succcount = 0;
                if ("success".equals(code)) {
                    JSONObject retrunData = JSONObject.parseObject(resultJson.getString("data"));
                    message += Util.null2String(retrunData.getString("MESSAGE"));
                    String data = Util.null2String(retrunData.getString("DATA"));
                    JSONArray dataList = JSONArray.parseArray(data);
                    for (int i = 0; i < dataList.size(); i++) {
                        JSONObject dataJson = dataList.getJSONObject(i);
                        String code1 = Util.null2String(dataJson.getString("CODE"));
                        String msg = Util.null2String(dataJson.getString("MSG"));
                        String serialId = Util.null2String(dataJson.getString("SERIAL_ID"));
                        if ("1".equals(code1)) {
                            rs.executeUpdate("update uf_zjjhhzb set czzt=1,msg=?,type=? where jhid=?", msg, code1, serialId);
                            failcount++;
                        }
                        if ("2".equals(code1)) {
                            succcount++;
                            rs.executeUpdate("update uf_zjjhhzb set czzt=0 where jhid=?", serialId);
                        }
                    }
                    jsonData.put("failcount", failcount);
                    jsonData.put("succcount", succcount);
                    apidatas.put("data", jsonData);
                }
            }

        } catch (Exception e) {
            code = "fail";
            writeLog(">>>>>pushZjjhhzData>>>Exception=" + e);
        }
        apidatas.put("code", code);
        apidatas.put("message", message);
        writeLog(">>>>>pushZjjhhzData>>>apidatas=" + apidatas.toString());
        return JSONObject.toJSONString(apidatas);
    }

    /**
     * @Description: 批量创建一般用款申请流程并提交
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023-12-31
     */
    @POST
    @Path("/batchCreateYbyksqWf")
    @Produces({MediaType.TEXT_PLAIN})
    public String batchCreateYbyksqWf(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String code = "success";
        String message = "";
        try {
            String formid = Util.null2String(request.getParameter("formid"));
            String ids = Util.null2String(request.getParameter("ids"));
            String curdate = DateUtil.getCurrentDate();
            RecordSet rs = new RecordSet();
            ResourceComInfo comInfo = new ResourceComInfo();
            rs.executeQuery("select * from uf_zjjhhzb where id in (" + ids + ") and nvl(sfcffklc,1) != 0");
            int totalcount = rs.getCounts();
            int succcount = 0;
            int failcount = 0;
            String requestid = "0";
            while (rs.next()) {
                String id = Util.null2String(rs.getString("id"));
                String ywqrr = Util.null2String(rs.getString("ywqrr"));
                //String jbr = Util.null2String(rs.getString("jbr"));
                String bm = Util.null2String(rs.getString("bm"));
                String jyzfnr = Util.null2String(rs.getString("jyzfnr"));
                String zffsxl = Util.null2String(rs.getString("zffsxl"));
                String cwfhjeyb = Util.null2String(rs.getString("cwfhjeyb"));
                String ksbm = Util.null2String(rs.getString("ksbm"));
                String ksmc = Util.null2String(rs.getString("ksmc"));
                String lxhdh = Util.null2String(rs.getString("lxhdh"));
                String khyxdh = Util.null2String(rs.getString("khyxdh"));
                String yxzhdh = Util.null2String(rs.getString("yxzhdh"));
                String lxhcd = Util.null2String(rs.getString("lxhcd"));
                String khyxcd = Util.null2String(rs.getString("khyxcd"));
                String yxzhcd = Util.null2String(rs.getString("yxzhcd"));

                String zjmxxmwb = Util.null2String(rs.getString("zjmxxmwb"));
                String jhid = Util.null2String(rs.getString("jhid"));
                String lzdjh = Util.null2String(rs.getString("lzdjh"));
                String bz = Util.null2String(rs.getString("bz"));
                String gsdm = Util.null2String(rs.getString("gsdm"));
                String ssgs = EcDataUtil.getGsxx(gsdm);
                String wlkmbm = Util.null2String(rs.getString("wlkmbm"));
                String wlkmbs = Util.null2String(rs.getString("wlkmbs"));
                String ysbm = Util.null2String(rs.getString("ysbm"));
                String ysxm = Util.null2String(rs.getString("ysxm"));
                String ydzqysfyeyb = Util.null2String(rs.getString("ydzqysfyeyb"));
                String cwfhjebb = Util.null2String(rs.getString("cwfhjebb"));
                String yfpzhjnd = Util.null2String(rs.getString("yfpzhjnd"));
                String yfpzxxmbh = Util.null2String(rs.getString("yfpzxxmbh"));
                String zjmxxm = Util.null2String(rs.getString("zjmxxm"));

                String username = comInfo.getLastname(ywqrr);
                Map<String, String> wf = EcDataUtil.getWorkflowId(formid);
                String workflowname = Util.null2String(wf.get("workflowname"));
                String requestname = workflowname+"-" + username + "-" + curdate;
                String workflowid = Util.null2String(wf.get("workflowid"));
                Map<String, String> requestMainMap = new HashMap<>();
                requestMainMap.put("jbr", ywqrr);
                requestMainMap.put("jbrwb", comInfo.getLastname(ywqrr));
                requestMainMap.put("bm", bm);
                requestMainMap.put("gh", comInfo.getWorkcode(ywqrr));
                requestMainMap.put("sqrq", curdate);
                requestMainMap.put("yksxfl", "0");
                requestMainMap.put("qwzfrq", DateUtil.getLastDayOfMonth(curdate));
                requestMainMap.put("yksxsm", jyzfnr);
                requestMainMap.put("zffs", EcDataUtil.convertZflx(zffsxl));
                requestMainMap.put("hkfyqtxfksxbzdfyxxjljd", jyzfnr);
                requestMainMap.put("bcqkjehjxx", cwfhjeyb);
                String gysid = Util.null2String(EcDataUtil.getGysId(ksbm).get("gysid"));
                requestMainMap.put("skdwxz", gysid);
                requestMainMap.put("skdwmc", Util.null2String(EcDataUtil.getGysId(ksbm).get("gysqc")));
                requestMainMap.put("gsdm", gsdm);
                requestMainMap.put("ssgs", ssgs);
                requestMainMap.put("ksbm", ksbm);
                requestMainMap.put("bzxz", "21");
                JSONObject gysyhxx =EcDataUtil.getGysYhxx(gysid,"CNY");
                requestMainMap.put("lxh", gysyhxx.getString("lxhdh"));
                requestMainMap.put("khx", gysyhxx.getString("khyxdh"));
                requestMainMap.put("zh", gysyhxx.getString("yxzhdh"));
                requestMainMap.put("lxhcd", gysyhxx.getString("lxhcd"));
                requestMainMap.put("khxcd", gysyhxx.getString("khyxcd"));
                requestMainMap.put("yxzhcd", gysyhxx.getString("yxzhcd"));
                requestMainMap.put("pldb", "0");
                requestid = EcDataUtil.WorkflowCreateByRequestMap(ywqrr, workflowid, requestname, "0", requestMainMap);
                if (Util.getIntValue(requestid, -1) > 0) {
                    String tablename = "formtable_main_" + formid;
                    String newmainid = EcDataUtil.getMainidByRequestid(requestid, tablename);
                    Map<String, Object> map = new HashMap<>();
                    map.put("zjjhxh", id);
                    map.put("ly", "EC");
                    map.put("zjmxxmwb", zjmxxmwb);
                    map.put("zjjhxhwb", jhid);
                    map.put("skdwdm", ksbm);
                    map.put("skdw", ksmc);
                    map.put("lzdjh", lzdjh);
                    map.put("bz", bz);
                    map.put("gsdm", gsdm);
                    map.put("wlkmbh", wlkmbm);
                    map.put("wlkm", wlkmbs);
                    map.put("yydmxjlm", ysbm);
                    map.put("xjlkm", ysxm);
                    map.put("ydzqysfyeyb", ydzqysfyeyb);
                    map.put("jeyb", cwfhjeyb);
                    map.put("bcqkjeyb", cwfhjeyb);
                    map.put("hl", "1");
                    map.put("bcqkjebb", cwfhjebb);
                    map.put("pldb", "0");
                    map.put("yfpzhjnd", yfpzhjnd);
                    map.put("yfpzxxmbh", yfpzxxmbh);
                    map.put("zjmxxm", zjmxxm);
                    map.put("jyzfnr", jyzfnr);
                    map.put("mainid", newmainid);
                    boolean flag = EcDataUtil.insertDetailData(tablename + "_dt1", map);
                    if (flag) {
                        rs.executeUpdate("update uf_zjjhhzb set sfcffklc=0 where id=?", id);
                        succcount++;
                    } else {
                        failcount++;
                    }
                } else {
                    failcount++;
                }
            }
            JSONObject jsonData = new JSONObject();
            jsonData.put("totalcount", totalcount);
            jsonData.put("succcount", succcount);
            jsonData.put("failcount", failcount);
            apidatas.put("data", jsonData);
        } catch (Exception e) {
            code = "fail";
            writeLog(">>>>>batchCreateYbyksqWf>>>Exception=" + e);
        }
        apidatas.put("code", code);
        apidatas.put("message", message);
        writeLog(">>>>>batchCreateYbyksqWf>>>apidatas=" + apidatas.toString());
        return JSONObject.toJSONString(apidatas);
    }

    /**
     * @Description: 资金计划汇总台账点击批量审批更新对应流程明细数据并提交流程
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023-12-31
     */
    @POST
    @Path("/batchSubmitXglc")
    @Produces({MediaType.TEXT_PLAIN})
    public String batchSubmitXglc(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String code = "success";
        String message = "";
        try {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select a.xglc from (select xglc from uf_zjjhhzb where zt=0 group by xglc) a," +
                    "workflow_requestbase b where a.xglc=b.requestid and b.currentnodetype<3");
            int totalcount = rs.getCounts();
            int succcount = 0;
            int failcount = 0;
            while (rs.next()) {
                String xglc = Util.null2String(rs.getString("xglc"));
                boolean flag = EcDataUtil.updateZjjhtbshDtl(xglc);
                if (flag) {
                    boolean status = EcDataUtil.autoSubmit(xglc);
                    if (status) {
                        String tablename = EcDataUtil.getTableName(xglc);
                        if("formtable_main_4736".equals(tablename)){
                            EcDataUtil.getSrmPMPBack(xglc,tablename);
                        }
                        succcount++;
                    } else {
                        failcount++;
                    }
                }
            }
            JSONObject jsonData = new JSONObject();
            jsonData.put("totalcount", totalcount);
            jsonData.put("succcount", succcount);
            jsonData.put("failcount", failcount);
            apidatas.put("data", jsonData);
        } catch (Exception e) {
            code = "fail";
            writeLog(">>>>>batchSubmitXglc>>>Exception=" + e);
        }
        apidatas.put("code", code);
        apidatas.put("message", message);
        writeLog(">>>>>batchSubmitXglc>>>apidatas=" + apidatas.toString());
        return JSONObject.toJSONString(apidatas);
    }

    /**
     * @Description: 用款台账点击批量提交更新状态并提交流程
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023-12-31
     */
    @POST
    @Path("/batchSubmitYktzWf")
    @Produces({MediaType.TEXT_PLAIN})
    public String batchSubmitYktzWf(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String code = "success";
        String message = "";
        try {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select a.id,a.fklc from (select id,fklc from uf_ybyktz where sfyzfwc=0 and nvl(lctjzt,1)=1 group by fklc,id) a," +
                    "workflow_requestbase b where a.fklc=b.requestid and b.currentnodetype<3");
            int totalcount = rs.getCounts();
            int succcount = 0;
            int failcount = 0;
            while (rs.next()) {
                String fklc = Util.null2String(rs.getString("fklc"));
                String id = Util.null2String(rs.getString("id"));
                boolean status = EcDataUtil.autoSubmit(fklc);
                if (status) {
                    rs.executeUpdate("update uf_ybyktz set lctjzt=0 where id=?", id);
                    String tablename = EcDataUtil.getTableName(fklc);
                    if("formtable_main_4734".equals(tablename)){
                        EcDataUtil.getSrmPMPBack(fklc,tablename);
                    }
                    succcount++;
                } else {
                    failcount++;
                }

            }
            JSONObject jsonData = new JSONObject();
            jsonData.put("totalcount", totalcount);
            jsonData.put("succcount", succcount);
            jsonData.put("failcount", failcount);
            apidatas.put("data", jsonData);
        } catch (Exception e) {
            code = "fail";
            writeLog(">>>>>batchSubmitYktzWf>>>Exception=" + e);
        }
        apidatas.put("code", code);
        apidatas.put("message", message);
        writeLog(">>>>>batchSubmitYktzWf>>>apidatas=" + apidatas.toString());
        return JSONObject.toJSONString(apidatas);
    }

}
